package problem;

public class S_129 {

      public class TreeNode {
         int val;
          TreeNode left;
          TreeNode right;
          TreeNode(int x) { val = x; }
      }

    class Solution {
        int res = 0;
        int num = 0;

        public int sumNumbers(TreeNode root) {
            pathSums(root);
            return res;
        }

        public int pathSums(TreeNode root) {
            if (root == null) return 0;
            num = num * 10 + root.val;

            if (root.left == null && root.right == null) res += num;

            pathSums(root.left);
            pathSums(root.right);

            num /= 10;
            return res;
        }
    }

    class Solution1{
        int sumNum = 0;

        public int sumNumbers(TreeNode root) {
            if (root == null)
                return 0;
            helper(root, 0);
            return sumNum;
        }

        public void helper(TreeNode root, int sum) {
            if (root.left == null && root.right == null) {
                sumNum += sum + root.val;
            }
            if (root.left != null)
                helper(root.left, sum * 10 + root.val * 10);
            if (root.right != null)
                helper(root.right, sum * 10 + root.val * 10);
        }

    }
}
